package com.xing.libao.init;

import com.xing.libao.util.RequestUtil;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: xingzhe
 * Date: 2015/8/17
 * Time: 17:18
 */
public class HuaFang {
    public static void main(String[] args) {
        showAllReply("http://www.huafangwang.net/thread-15392-1-1.html");
    }

    public static void warningList() {
        RequestUtil requestUtil = RequestUtil.getInstance();
        for (int i = 1; i < 10; i++) {
            String content = requestUtil.getHtml("http://www.huafangwang.net/forum-39-" + i + ".html");
            Document document = Jsoup.parse(content);
            Elements elements = document.getElementsByTag("a");
            for (Element element : elements) {
                String href = element.attr("href");
                String text = element.text();
                if (href.contains("thread-") && text.length() > 5) {
                    System.out.println(element.text() + " --- " + element.attr("href"));
                }
            }
        }
    }

    public static void showAllReply(String url) {
        RequestUtil requestUtil = RequestUtil.getInstance();
        String content = requestUtil.getHtml(url);
        int pageCount = 0;
        Pattern pattern = Pattern.compile("共 (.*?) 页");
        Matcher matcher = pattern.matcher(content);
        String page = "";
        if (matcher.find()) {
            page = matcher.group(1);
        }
        if (StringUtils.isNumeric(page)) {
            pageCount = Integer.parseInt(page);
            String first = url.substring(0, url.indexOf("-1-1") + 1);
            String second = "-1.html";
            for (int i = 1; i < pageCount; i++) {
                System.out.println(first + i + second);
                content = requestUtil.getHtml(first + i + second);
                if(StringUtils.isNotEmpty(content)) {
                    Document document = Jsoup.parse(content);
//                    Elements elements = document.select("div.t_fsz");
                    Elements elements = document.select("tbody>tr");
                    for (Element element : elements) {
                        if(element.select("p>em>a").first()!=null && element.select("div.t_fsz").first()!=null) {
                            String name = element.select("p>em>a").first().text();
                            String text = element.select("div.t_fsz").first().text();
                            System.out.println(text + "---" + name);
                        }
                    }
                }
            }
        }
    }
}
